package com.douqu.game.core.entity.ext.data.challenge;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.config.challenge.InstanceConfig;
import com.douqu.game.core.config.challenge.LevelConfig;
import com.douqu.game.core.entity.EntityObject;
import com.douqu.game.core.entity.db.InstanceDB;
import com.douqu.game.core.entity.db.InstanceListDB;
import com.douqu.game.core.entity.db.LevelDB;
import com.douqu.game.core.entity.ext.data.BaseData;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.util.CoreUtils;
import com.douqu.game.core.util.LogUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: Bean
 * @Description:
 * @Date: 2017-10-24 16:21
 */
public class InstanceData extends BaseData {


    /**
     * 缓存副本挑战结算信息，等待客户端调用
     */
    public PassLevelCache responseTemp;
    /**
     * <难度， 副本列表>
     */
    private Map<Integer, InstanceListDB> instanceListMap = new ConcurrentHashMap<>();

    @Override
    public void init() {

    }

    @Override
    public void checkInit() {

    }

    @Override
    public void reset() {

    }

    @Override
    public void checkReset() {

    }

    @Override
    public void writeTo(ByteBuffer buffer) {
        buffer.writeShort(instanceListMap.size());
        for (Map.Entry<Integer, InstanceListDB> entry : instanceListMap.entrySet()) {
            buffer.writeInt(entry.getKey());
            entry.getValue().writeTo(buffer);
        }

        buffer.writeBoolean(false);
    }

    @Override
    public void loadFrom(ByteBuffer buffer) {
        int size = buffer.readShort();
        int key;
        for (int i = 0; i < size; i++) {
            key = buffer.readInt();
            InstanceListDB listDB = new InstanceListDB();
            listDB.loadFrom(buffer);
            instanceListMap.put(key, listDB);
        }
        buffer.readBoolean();
    }

    public InstanceListDB getInstanceList(int key) {
        return instanceListMap.get(key);
    }


    /**
     * 根据副本id判断是否通过此副本
     *
     * @param instanceId
     * @return
     */
    public boolean isPassInstance(Integer instanceId) {
        for (Map.Entry<Integer, InstanceListDB> entry : instanceListMap.entrySet()) {
            for (InstanceDB instanceDB : entry.getValue().getInstanceList()) {
                if (instanceDB.getLevelMap().get(instanceId) != null) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取最近一次通过三种类型副本的id
     *  1:2,2:5,3:5
     * @return
     */
    public String getLastPass(){
        StringBuilder sb = new StringBuilder();
        List<InstanceDB> instanceDBList = null;
        List<LevelDB> levelDBList = null;
        for (Map.Entry<Integer,InstanceListDB> entry:instanceListMap.entrySet()){
            sb.append(entry.getKey());
            sb.append(ConstantFactory.COLON);
            instanceDBList = entry.getValue().getInstanceList();
            if (instanceDBList.isEmpty()){
                sb.append(ConstantFactory.NULL);
            }else{
                levelDBList = instanceDBList.get(instanceDBList.size() - 1).getFinishLevelDbs();
                if (levelDBList.isEmpty()){
                    sb.append(ConstantFactory.NULL);
                }else{
                    sb.append(levelDBList.get(levelDBList.size() - 1).id);
                }
            }
            sb.append(ConstantFactory.COMMA);
        }
        return sb.toString();
    }

    /**
     * 是否是通过新的关卡
     *
     * @param type
     * @param mapId
     * @param levelId
     * @param stars
     * @return
     */
    public boolean addPassLevel(int type, int mapId, int levelId, int stars) {
        InstanceListDB instanceListDB = getInstanceList(type);
        if (instanceListDB == null) {
            InstanceListDB listDB = new InstanceListDB();
            instanceListMap.put(type, listDB);
            InstanceDB instanceDb = new InstanceDB(mapId);
            listDB.addInstanceMap(instanceDb);
            LevelDB levelDB = new LevelDB(levelId);
            levelDB.setMaxStars(stars);
            instanceDb.addLevel(levelDB);
            return true;
        } else {
            InstanceDB instanceDb = instanceListDB.getInstanceMap(mapId);
            if (instanceDb == null) {
                instanceDb = new InstanceDB(mapId);
                instanceListDB.addInstanceMap(instanceDb);
                LevelDB levelDB = new LevelDB(levelId);
                levelDB.setMaxStars(stars);
                instanceDb.addLevel(levelDB);
                return true;
            } else {
                LevelDB levelDB = instanceDb.getLevelMap().get(levelId);
                if (levelDB == null) {
                    levelDB = new LevelDB(levelId);
                    instanceDb.addLevel(levelDB);
                    levelDB.setMaxStars(stars);
                    return true;
                } else {//重复关卡
                    if (CoreUtils.getStarNum(stars) >= CoreUtils.getStarNum(levelDB.getMaxStars())) {
                        levelDB.setMaxStars(stars);
                        return false;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 能不能打
     *
     * @param type
     * @param chapterId
     * @param levelId
     */
    public boolean canPassLevel(int type, int chapterId, int levelId) {
        InstanceListDB instanceListDB = getInstanceList(type);
        if (instanceListDB == null) {
            if (getFirstInstance(type).id == chapterId && getFirstInstance(type).levels[0] == levelId) {
                return true;
            } else {
                return false;
            }
        } else {
            InstanceDB instanceDB = instanceListDB.getInstanceMap().get(chapterId);
            if (instanceDB == null) {
                InstanceConfig config = DataFactory.getInstance().getGameObject(DataFactory.INSTANCE_KEY, chapterId);
                if (config.levels[0] != levelId) {
                    return false;
                }
                for (InstanceDB db : instanceListDB.getInstanceList()) {
                    if (db.getConfig().unLockInstance == chapterId) {
                        if (db.getFinishLevelDbs().size() == db.getConfig().levels.length) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
                return false;
            } else {
                if (!instanceDB.getConfig().hasLevel(levelId)) {
                    return false;
                }
                if (instanceDB.getLevelMap().get(levelId) != null || instanceDB.getNextLevel() == levelId) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    public InstanceConfig getFirstInstance(int type) {
        List<InstanceConfig> list = DataFactory.getInstance().getDataList(DataFactory.INSTANCE_KEY);
        for (InstanceConfig config : list) {
            if (config.type == type) {
                return config;
            }
        }
        return null;
    }


    public boolean hasRedPointRemind() {
        for (InstanceListDB instanceListDB : instanceListMap.values()) {
            if (instanceListDB.hasRedPointRemind()) {
                return true;
            }
        }

        return false;
    }

    public Map<Integer, InstanceListDB> getInstanceListMap() {
        return instanceListMap;
    }

    public InstanceListDB getInstanceListDB(int difficult) {
        return instanceListMap.get(difficult);
    }

    public boolean levelHasPass(int levelId) {
        LevelConfig config = DataFactory.getInstance().getGameObject(DataFactory.LEVEL_KEY, levelId);
        if (config == null) {
            return false;
        }
        InstanceConfig instanceConfig = DataFactory.getInstance().getGameObject(DataFactory.INSTANCE_KEY, config.getInstanceId());
        if (instanceConfig == null) {
            LogUtils.error("InstanceConfig is null -> " + config.getInstanceId() + " " + config.getName());
            return false;
        }

        InstanceListDB listDB = instanceListMap.get(instanceConfig.type);
        if (listDB == null) {
            return false;
        }

        InstanceDB instanceDB = listDB.getInstanceMap(instanceConfig.id);
        if (instanceDB == null) {
            return false;
        }
        if (instanceDB.containsLevel(levelId)) {
            return true;
        }
        return false;
    }

    public int getTotalStart() {
        int sum = 0;
        for (InstanceListDB instanceListDB : instanceListMap.values()) {
            sum += instanceListDB.getTotalStars();
        }
        return sum;
    }

    /**
     * 根据类型获得当前最高通关关卡
     * @param type
     * @return
     */
    public int getMaxInstance(int type){
        //获得已通过关卡对象
        InstanceListDB instanceListDB = getInstanceList(type);
        if(instanceListDB == null){
            return 0;
        }
        //章节id
        int maxId = 0;
        //关卡id
        int maxCardId = 0;
        Map<Integer, InstanceDB> dbMap = instanceListDB.getInstanceMap();
        //取出最大章节
        for (Map.Entry<Integer,InstanceDB> entry:dbMap.entrySet()){
            if (maxId< entry.getKey()){
                maxId = entry.getKey();
            }
        }
        if (maxId == 0){
            return 0;
        }
        InstanceDB instanceDB = dbMap.get(maxId);
        List<LevelDB> levelDBs = instanceDB.getFinishLevelDbs();
        for (LevelDB levelDB : levelDBs){
            if (maxCardId<levelDB.id){
                maxCardId= levelDB.id;
            }
        }
        return maxCardId;
    }


    public static class PassLevelCache extends EntityObject {
        public int mapId;
        public int levelId;
        public int stars;
        public boolean firstPass;

        public PassLevelCache(int mapId, int levelId, int stars, boolean firstPass) {
            this.mapId = mapId;
            this.levelId = levelId;
            this.stars = stars;
            this.firstPass = firstPass;
        }



        @Override
        public String toString() {
            return "PassLevelCache{" +
                    "mapId=" + mapId +
                    ", levelId=" + levelId +
                    ", stars=" + stars +
                    '}';
        }
    }


}
